package server;

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import pojo.Wrapper;

import java.io.*;
import java.nio.file.Watchable;
import java.util.*;

/**
 * @author chenx
 * @date 2021/8/28-14:02
 */
public class Service {
    private static  List<Wrapper> servletList = new ArrayList<Wrapper>();

    public List<Wrapper> getServletList() {
        return servletList;
    }

    public static void main(String[] args) {
        Service mapper = new Service();
        mapper.loadEngin();
        for (Wrapper key: servletList){
            System.out.println(key);
        }
    }


    /**
     * 加载解析server.xml,初始化 Engine
     *
     */
    public void loadEngin(){
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//service");
            for (int i = 0; i < selectNodes.size(); i++){
                Element element = selectNodes.get(i);
                //Connector
                Element connector = (Element)element.selectSingleNode("Connector");
                //port
                Integer port = Integer.valueOf(connector.attributeValue("port"));
                //Engine
                Element engine = (Element)element.selectSingleNode("Engine");
                //Host
                Element host = (Element)engine.selectSingleNode("Host");
                String hostName = host.attributeValue("name");
                String appBase = host.attributeValue("appBase");
                //锁定web.xml
                File dir = new File(appBase);
                getWebXml(hostName,dir,appBase);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getWebXml(String host,File dir,String appBase) throws FileNotFoundException {
        File[] files = dir.listFiles(new FileFilter(){
            @Override
            public boolean accept(File pathname) {
                return "web.xml".equals(pathname.getName())||pathname.isDirectory();
            }
        });
        for (File file : files) {
            if (file.isFile()) {
                Wrapper wrapper = new Wrapper();
                wrapper.setHost(host);
                System.out.println("文件名:" + file.getAbsolutePath());
                String absolutePath = file.getAbsolutePath();
                String context = absolutePath.substring(appBase.length(),absolutePath.indexOf("web.xml")-1);
                System.out.println("context:" + context);
                wrapper.setContext(context);
                loadServlet(file.getAbsolutePath(),wrapper);
                servletList.add(wrapper);
            }else{
                //递归
               getWebXml(host,file,appBase);
            }
        }
    }

    public void loadServlet(String file,Wrapper wrapper) throws FileNotFoundException {
        InputStream resourceAsStream = new FileInputStream(file);
        try {
            resourceAsStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /my
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                WebClassLoader webClassLoader = new WebClassLoader();
                Class<?> aClass = webClassLoader.findClass(file.substring(0,file.indexOf("web.xml")), servletClass);
                wrapper.setServlet((HttpServlet)aClass.getDeclaredConstructor().newInstance());
                //servletMap.put(urlPattern, (HttpServlet)aClass.getDeclaredConstructor().newInstance());
                //servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
